"ui";
let jsBridge = files.read(files.cwd() + "/views/webview/jsBridge.ts");
let vConsole = files.read(files.cwd() + "/views/webview/vconsole.min.ts");
/** autojs处理事件 */
const autojsHandler = {};
ui.layout(
  <linear w="*" h="*">
    <webview id="webView" w="*" h="*" />
  </linear>
);

function debugModel(open) {
  if (open) {
    // 开启debug模式，需要在电脑浏览器上访问 chrome://inspect/#devices
    android.webkit.WebView.setWebContentsDebuggingEnabled(true);
    console.log("开启debug模式，可以在电脑浏览器上访问 chrome://inspect/#devices")
  }
}
/**
 * 初始化jsbridge
 * @param {*} webViewWidget 
 * @param {*} supportVConsole 
 */
function __initJsBridge__(webViewWidget, supportVConsole) {
  let webSettings = webViewWidget.getSettings();
  webSettings.setLayoutAlgorithm(android.webkit.WebSettings.LayoutAlgorithm.NORMAL);
  webSettings.setUseWideViewPort(true);
  webSettings.setLoadWithOverviewMode(true);

  webViewWidget.webViewClient = new JavaAdapter(android.webkit.WebViewClient, {
    onPageFinished: (webView, curUrl) => {
      // console.log('页面加载完成');
      try {
        if (supportVConsole) {
          __callJavaScript__(webView, vConsole + ";const vconsole = new VConsole();", null);
        }
        // 注入 jsBridge
        // console.log('注入： ' + jsBridge)
        __callJavaScript__(webView, jsBridge, null);
        // if (jsFileList instanceof Array) {
        //   jsFileList.forEach((file, index) => {
        //     try {
        //       let js = files.read(file);
        //       callJavaScript(webView, js, (val) => {
        //         // console.log("脚本注入成功: " + file);
        //       });
        //     } catch (e) {
        //       toastLog("脚本注入失败: " + file);
        //       console.trace(e);
        //     }
        //   });
        // }
      } catch (e) {
        console.trace(e)
      }
    },
    shouldOverrideUrlLoading: (webView, request) => {
      let url = '';
      try {
        url = (request.a && request.a.a) || (request.url);
        if (url instanceof android.net.Uri) {
          url = url.toString();
        }
        if (url.startsWith("jsbridge://")) {
          let uris = url.split("/");
          let cmd = uris[2];
          let callId = uris[3];
          let params = java.net.URLDecoder.decode(uris[4], "UTF-8");
          // 异步调度
          threads.start(function() {
            // console.log('AutoJs处理JavaScript调用请求: callId=%s, cmd=%s, params=%s', callId, cmd, params);
            let result = {success: true, data: null};
            try {
              let fun = autojsHandler[cmd];
              if (!fun) {
                throw new Error('未注册autojs处理事件：' + cmd);
              }
              result.data = fun(JSON.parse(params)) || null;
            } catch (e) {
              console.trace(e);
              result = { success: false, message: e.message };
            }
            // console.log('autojs处理网页请求结果： cmd=' + cmd + ', 返回：' + JSON.stringify(result));
            // webView.post(function() {
            ui.post(function() {
              webView.loadUrl("javascript:window.AutoJs.callback({'callId':" + callId + ", 'params': " + JSON.stringify(result) + "});");
            });
          })
        } else if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("file://") || url.startsWith("ws://") || url.startsWith("wss://")) {
          webView.loadUrl(url);
        } else {
          confirm("允许网页打开APP？").then(value => {
            //当点击确定后会执行这里, value为true或false, 表示点击"确定"或"取消"
            if (value) {
              let uri = android.net.Uri.parse(url);
              app.startActivity(new Intent(Intent.ACTION_VIEW).setData(uri).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
            }
          });
        }
        // 返回true代表自定义处理，返回false代表触发webview加载
        return true;
      } catch (e) {
        if (e.javaException instanceof android.content.ActivityNotFoundException) {
          webView.loadUrl(url);
        } else {
          console.trace(e);
          toastLog('无法打开URL: ' + url);
        }
      }
    },
    // shouldInterceptRequest: (webView, request) => {
    //     try {
    //         let uris = request.a.a.split("/");
    //         if (uris[2] == "jsbridge") {
    //             let cmd = uris[3];
    //             let params = java.net.URLDecoder.decode(uris[4], "UTF-8");
    //             return handleJsBridge(cmd, params);
    //         }
    //     } catch (e) {
    //         console.trace(e);
    //     }
    // },
    onReceivedError: (webView, webResourceRequest, webResourceError) => {
      let url = webResourceRequest.getUrl();
      let errorCode = webResourceError.getErrorCode();
      let description = webResourceError.getDescription();
      console.trace(errorCode + " " + description + " " + url);
    }
  });
  webViewWidget.webChromeClient = new JavaAdapter(android.webkit.WebChromeClient, {
    onConsoleMessage: (msg) => {
      console.log("[%s:%s]: %s", msg.sourceId(), msg.lineNumber(), msg.message());
    }
  });
}
// 设置界面沉浸式 适配虚拟导航栏
function immersionUI() {
  ui.statusBarColor(colors.TRANSPARENT);  
  let options = android.view.View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
  activity.getWindow().getDecorView().setSystemUiVisibility(options);
  // activity.getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
  // 顶部状态栏 
  // activity.getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
  // 底部导航栏
  // activity.getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}

// 支持二次退出
let lastExitTime = 0;
function support2Exit(webViewUI) {
  webViewUI.setOnKeyListener(new JavaAdapter(android.view.View.OnKeyListener, {
    onKey: (webView, keyCode, event) => {
      if ((event.getAction() == android.view.KeyEvent.ACTION_DOWN) && (keyCode == android.view.KeyEvent.KEYCODE_BACK)) {
        // console.log('点击了返回，上一页：' + webView.canGoBack())
        if (webView.canGoBack()) {
          //后退
          webView.goBack();
        } else {
          let curTime = new Date().getTime();
          if (curTime - lastExitTime > 1000) {
            toast('再次返回可退出');
            lastExitTime = curTime;
            isFirstPage = true;
          } else {
            exit();
          }
        }
        return true;
      }
      return false;
    }
  }));
}
/**
 * 获取UI控件
 */
function getUI() {
  return ui.webView;
}
/** 
 * 加载url
 * @param {string} url  
 * @param {boolean} debug 是否开启debug模式
 * @returns webView UI控制
 */
function loadUrl(url, debug) {
  // 开启沉浸式，必须在webview 加载html前设置
  immersionUI();
  debugModel(debug);
  support2Exit(ui.webView);
  // 启用webview与autojs通讯能力
  __initJsBridge__(ui.webView, debug);
  ui.webView.loadUrl(url);
  return ui.webView;
}
/** 绑定autojs事件 */
function bindFuntion(eventName, callback) {
  if (!eventName) {
    console.warn('跳过无效autojs页面处理事件名【' + eventName + '】');
    return;
  }
  if (typeof (callback) != 'function') {
    console.warn('绑定autojs【' + eventName + '】事件第2参数需要一个回调函数，实际是' + typeof (callback));
    return;
  }
  let oldCallback = autojsHandler[eventName];
  if (oldCallback) {
    console.log('替换autojs页面处理事件：' + eventName);
  } else {
    console.log('注册autojs页面处理事件：' + eventName);
  }
  autojsHandler[eventName] = callback;
}
/** 推送给页面数据 */
function pushData(cmd, params) {
  console.log('推送命令【' + cmd + '】参数【' + JSON.stringify(params) + '】');
  let js = "" +
  "if (typeof(autojsPush) == 'function') { " +
  "   autojsPush('" + cmd + "', " + JSON.stringify(params) + ");" +
  "} else { " +
  "   console.error('HTML不存在autojsPush函数');" +
  "}";
  return __callJavaScript__(ui.webView, js);
}
/**
 * 执行html脚本
 * @param {*} webViewWidget 
 * @param {*} script 
 * @param {*} callback 
 */
function __callJavaScript__(webViewWidget, script) {
  return new Promise((resolve, reject) => {
    try {
      console.assert(webViewWidget != null, "webView控件为空");
      webViewWidget.evaluateJavascript("javascript:" + script, new JavaAdapter(android.webkit.ValueCallback, {
        onReceiveValue: (val) => {
          // console.log('执行js【' + script + '】返回 ' + JSON.stringify(val));
          resolve(val);
        }
      }));
    } catch (e) {
      console.trace(e);
      reject(e);
    }
  }); 
  
}

/**
 * 默认初始化，加载index.html 页面，返回ui webview 控件对象
 */
function defaultInit() {
  let autojsCmd = require(files.cwd() + "/views/webview/autojsCmd.js");
  let htmlCmd = require(files.cwd() + "/views/webview/htmlCmd.js");
  
  // 绑定autojs提供给html的命令
  Object.keys(autojsCmd).forEach(cmd => {
      htmlView.bind(cmd, autojsCmd[cmd]);
  });
  // 绑定autojs推送给页面的命令
  htmlCmd.addPusher(this);
  // 加载页面
  let url = "file://" + files.cwd() + '/views/index.html';
  // 
  htmlView.loadUrl(url, false);
  return getUI();
}

module.exports = {
  getUI: getUI,
  loadUrl: loadUrl,
  bind: bindFuntion,
  push: pushData,
  defaultInit: defaultInit,
}